package com.coin900.coin.cmd.notice;

import com.coin900.coin.cmd.ACmd;
import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.code.RespCode;
import com.coin900.coin.persist.coin.CoinNoticeVO;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.service.coin.ICoinNoticeService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shui
 * @create 2018-02-05
 **/
@Controller
public class CoinNoticePutCmd extends ACmd {
    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        FuUserVO user = super.getUser(sign);
        String source = sign.getSource();
        CoinNoticeVO coinNoticeVO = new Gson().fromJson(source, CoinNoticeVO.class);
        Long id = coinNoticeVO.getId();
        Map<String, Object> params = new HashMap<>();
        if (id == null) {
            coinNoticeVO.setCreatedInfor(user);
            coinNoticeVO.setIsPublish(0);
            this.noticeService.insertCoinNotice(coinNoticeVO);
        } else {
            params.put("id", id);
            params.put("dataStatus", 1);
            List<CoinNoticeVO> coinNoticeVOS = this.noticeService.loadCoinNotice(params);
            if (coinNoticeVOS.isEmpty()) {
                respSign.setMsg("通知不存在");
                respSign.setRespCode(RespCode.FAIL);
                return respSign;
            }
            CoinNoticeVO dbNoticeVO = coinNoticeVOS.get(0);
            if (dbNoticeVO.getIsPublish().equals(1)) {
                respSign.setMsg("公告已发布");
                respSign.setRespCode(RespCode.FAIL);
                return respSign;
            }
            coinNoticeVO.setModifiedInfor(user);
            this.noticeService.updateCoinNotice(coinNoticeVO);
        }
        return respSign;
    }

    @Autowired
    private ICoinNoticeService noticeService;

    @Override
    public String getCmdCode() {
        return CmdCode.COIN_NOTICE_PUT;
    }
}
